package org.jod.anarchytrek.component;

import org.jod.anarchytrek.AComponent;
import org.jod.anarchytrek.ISupplierableComponent;
import org.jod.anarchytrek.ITimerableComponent;
import org.jod.anarchytrek.ITurnableComponent;
import org.jod.anarchytrek.componentfactory.WarpDriveClass;
import org.jod.anarchytrek.info.WarpDriveInfo;
import org.jod.anarchytrek.util.MathUtil;

public class WarpDrive extends AComponent implements ITimerableComponent, ITurnableComponent , ISupplierableComponent {

    private static final int STARTUP_TIMEOUT = 5;

    private int _minimunEnergyPoint;

    private int _maximumEnergyPoint;

    protected int _amountAvaiableEnergy;

    private String _status;

    private WarpDriveInfo _warpDriveInfo;

    private int _counterStartup;

	private boolean _adjust;

    public WarpDrive(WarpDriveInfo aWarpDriveInfo, WarpDriveClass aWarpDriveClass) {
        super(aWarpDriveClass.structuralUnits(), aWarpDriveInfo);
        _minimunEnergyPoint = aWarpDriveClass.minimunEnergyPoint();
        _maximumEnergyPoint = aWarpDriveClass.maximumEnergyPoint();
        _amountAvaiableEnergy = 0;
        _warpDriveInfo = aWarpDriveInfo;
        _status = OFFLINE;
        _counterStartup = 0;
        _adjust = true;
        toInfo();
    }


    public void timed() {
        if (!running())
            return;

        randomAvaiable();
        toInfo();
    }




    public void adjust() {
    	_adjust = true;
    }
    
    public int supply() {
        return energy();
    }  
    
    
    public void turnOn() {
        _amountAvaiableEnergy = 0;
        _status = STANDBY;
        toInfo();
    }



    public void turnOff() {
        _status = OFFLINE;
        _amountAvaiableEnergy = 0;
        _counterStartup = 0;
        toInfo();
    }
    


    protected void toInfo() {
        _warpDriveInfo.status(_status);
        _warpDriveInfo.avaiableEnergy(energy());
    }
    
    private boolean running() {
        _counterStartup += 1;
        if (_counterStartup == STARTUP_TIMEOUT) {
                    _status=ONLINE;
                    _counterStartup = 0;
        }
        return _status.equals(ONLINE);
    }    
    
    private int energy() {
        return _amountAvaiableEnergy;
    }



	private void randomAvaiable() {
		if (_adjust) {
			_amountAvaiableEnergy = MathUtil.randombetween(_minimunEnergyPoint, _maximumEnergyPoint);
			_adjust = false;
		}
	}


}
